/**
 * 第三步
 * 实验设计准备化学试剂
 *
 */
import { FC, useEffect, useState } from "react";
import { observer, inject } from "mobx-react";
import { useParams, useNavigate } from "react-router-dom";
import {
  Layout,
  Divider,
  Tooltip,
  Popover,
  Popconfirm,
  Spin,
  Modal,
  Typography,
  Space,
  Row,
  Col,
  Button,
  Table,
} from "antd";
import { ColumnsType } from "antd/es/table";
import { EditOutlined, DeleteOutlined } from "@ant-design/icons";
// import math, { FIXEDINDEX } from "../../utils/math";
import {
  createList,
  ROWWORD,
  BASEWIDE,
  BASEHEIGHT,
  RATE,
  MARGIN,
  ReactionSlotName,
} from "../../utils";
import StepTop from "./StepTop";
import ShelfMiniPlane from "./ShelfMiniPlane";
import MmPixBox from "../components/MmPixBox";
import BottlesPlane, { ReagentPop } from "./BottlesPlane";
import ReagentSlotModal from "./ReagentSlotModal";
// import ReagentAmount from "../components/ReagentAmount";

import { ReagentModal as AddReagentModal} from "../ReagentUser"

import { ITStore } from "../../store";
import {
  ITShelf,
  ITBottle,
  ITColumns,
  ITFillReagent,
} from "../../store/interfaces";
import "../Workbench/index.less";

interface TProp {
  store: ITStore;
}

interface ITShelfBottle {
  shelfInfo?: ITShelf | null;
  bottleInfo?: ITBottle | null;
}

interface ITShelfModal extends TProp {
  slotName: string;
  isShow: boolean;
  close: () => void;
}

interface ITColReagent {
  key: string;
}

const { Content } = Layout;
const { Link } = Typography;

// 试剂瓶列表和已添加试剂弹窗
const ShelfModal: FC<ITShelfModal | any> = inject("store")(
  observer(({ store, isShow, close, slotName }: ITShelfModal) => {
    const {
      languageStore: { lang, langCur },
      designerStore: {
        currentDesigner,
        currentSlotInfo,
        currentReagentsInfo,
        changShowReagentAddEditModal,
        changeReagentAddEditData,
        removeReagent,
      },
      shelfStore: { allShelf },
      globalStore: { mmPixRate },
      reagentStore: { getReagentInfoById, getReagentUnit,allReagent },
    } = store;

    const [modalWidth, setModalWidth] = useState<number>(1040);
    const [shelfInfo, setShelfInfo] = useState<any>(null);

    const [tableData, setTableData] = useState<any>([]);

    useEffect(() => {
      if (currentSlotInfo) {
        setShelfInfo(currentSlotInfo[slotName]);
      }
    }, [slotName, currentSlotInfo]);

    useEffect(() => {
      if (currentReagentsInfo) {
        const shelfReagents = currentReagentsInfo[slotName];
        let tempData: any = [];
        if (shelfReagents) {
          const bottles = Object.keys(shelfReagents);
          bottles.forEach((bName: string, index: number) => {
            let tmpReagentInfo = shelfReagents[bName];
            const { reagentId, mmol, weight, volume, type, id, defaultAmount } =
              tmpReagentInfo;
            const reagentInfo = getReagentInfoById(reagentId);
            if (reagentInfo) {
              const { name, cnname } = reagentInfo;
              const unit = getReagentUnit(reagentId, lang);
              let tempName = name;
              if (langCur === "zhcn") {
                tempName = cnname || name;
              }
              tempData.push({
                _id: id,
                id: reagentId,
                key: index,
                name: tempName,
                position: bName,
                fillType: type,
                mmol,
                weight,
                volume,
                defaultAmount,
                unit,
              });
            }
          });
        }
        setTableData(tempData);
      }
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [slotName, currentReagentsInfo, allReagent]);

    useEffect(() => {
      let modalWidth = 1040;
      const { shelf } = shelfInfo || {};

      let shelfWide = 0;

      allShelf.some((item) => {
        if (item.name === shelf) {
          shelfWide = item.length;
          return true;
        }
        return false;
      });

      modalWidth = shelfWide * mmPixRate + 560;

      setModalWidth(modalWidth);
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [mmPixRate, shelfInfo]);

    const closeModal = () => {
      close();
    };

    const modifyItem = (data: any) => {
      const { position, amount, id, defaultAmount } = data;
      changeReagentAddEditData({
        slotName,
        bottleName: position,
        reagent: {
          reagentId: id,
          amount,
          defaultAmount,
        },
      });
      changShowReagentAddEditModal(true);
    };

    const deleteItem = async (data: any) => {
      if (currentDesigner) {
        let { id } = currentDesigner;
        const { position } = data;
        await removeReagent({ slotName, bottleName: position, designerId: id });
      }
    };

    const columns: ITColumns[] = [
      // {
      //   title: lang["langshelf"],
      //   dataIndex: "shelfName",
      //   key: "shelfName",
      // },
      {
        title: lang["langreagentposi"],
        dataIndex: "position",
        key: "position",
      },
      {
        title: lang["langname"],
        dataIndex: "name",
        key: "name",
        render: (txt: string, record: any) => {
          const { position, id } = record;
          const reagentInfo = getReagentInfoById(id);
          return (
            <Popover
              title={position}
              content={<ReagentPop reagentInfo={reagentInfo} />}
            >
              <Link>{txt}</Link>
            </Popover>
          );
        },
      },
    //   {
    //     title: lang["langamount"],
    //     dataIndex: "defaultAmount",
    //     key: "defaultAmount",
    //     render: (_amount: ITFillReagent, record: any) => {
    //       const { type, weight, volume } = _amount;
    //       let tempAmount = null;
    //       if (type === 1) {
    //         tempAmount = volume;
    //       } else if (type === 2) {
    //         tempAmount = weight;
    //       }
    //       return (
    //         <Popover title="" content={<ReagentAmount data={_amount} />}>
    //           <Link>
    //             {tempAmount}
    //             {record.unit}
    //           </Link>
    //         </Popover>
    //       );
    //     },
    //   },
    //   {
    //     title: lang["langused"],
    //     dataIndex: "used",
    //     key: "used",
    //     render: (txt: any, record: any) => {
    //       return "";
    //       // return `${floatObj.subtract(record.defaultAmount, record.amount)}${
    //       //   record.unit
    //       // }`;
    //     },
    //   },
      {
        title: lang["langedit"],
        dataIndex: "edit",
        key: "edit",
        width: 110,
        align: "center",
        render: (txt: string, record: any) => {
          return (
            <Space>
              <Tooltip title={lang["langedit"]}>
                <Button
                  type="link"
                  icon={<EditOutlined />}
                  onClick={() => {
                    modifyItem(record);
                  }}
                />
              </Tooltip>
              <Popconfirm
                title={lang["langconfirmdel"]}
                onConfirm={() => {
                  deleteItem(record);
                }}
              >
                <Tooltip title={lang["langdelete"]}>
                  <Button
                    type="link"
                    danger
                    disabled={record.defaultAmount - record.amount > 0}
                    // loading={delData?.id === record.id && delShelfLoading}
                    icon={<DeleteOutlined />}
                  />
                </Tooltip>
              </Popconfirm>
            </Space>
          );
        },
      },
    ];

    return (
      <Modal
        title={
          <Row>
            <Col span={12}>
              <Space>
                {slotName}
                {lang["langstep3"]}
              </Space>
            </Col>
            <Col span={11}>
              <Space style={{ float: "right" }}>
                <MmPixBox />
              </Space>
            </Col>
            <Col span={1}></Col>
          </Row>
        }
        open={isShow}
        onCancel={closeModal}
        destroyOnClose={true}
        width={modalWidth}
        footer={
          <Button type="primary" onClick={closeModal}>
            {lang["langclose"]}
          </Button>
        }
      >
        <Row>
          <Col flex="480px" style={{ paddingRight: 10 }}>
            <Table
              dataSource={tableData}
              columns={columns}
              bordered
              size="small"
            />
          </Col>
          <Col flex="auto">
            <BottlesPlane shelfInfo={shelfInfo} slotName={slotName} />
          </Col>
        </Row>
      </Modal>
    );
  })
);

const DesignerWorkbenchPannel: FC<TProp | any> = inject("store")(
  observer(({ store }: TProp) => {
    const {
      languageStore: { lang, langCur },
      designerStore: {
        currentDesigner,
        changeCurrentWorkbench,
        currentWorkbench,
        currentSlotInfo,
        currentReactorSlotInfo,
      },
      workbenchStore: { getWorkbenchById },
      shelfStore: { allShelf },
      bottleStore: { allBottle },
    } = store;

    const [showLoading, setShowLoading] = useState<boolean>(true);

    const [rowList, setRowList] = useState<number[]>([]);

    const [columnList, setColumnList] = useState<number[]>([]);

    const [slotHeight, setSlotHeight] = useState<number>(0);

    const [slotWide, setSlotWide] = useState<number>(0);

    const [slotMargin, setSlotMargin] = useState<number>(0);

    const [slotShelf, setSlotShelf] = useState<any>(null);

    const [reactorSlotShelf, setReactorSlotShelf] = useState<any>(null);

    const [showShelfModal, setShowShelfModal] = useState<boolean>(false);

    const [popSlotName, setPopSlotName] = useState<string>("");

    useEffect(() => {
      setSlotHeight(BASEHEIGHT * RATE);
      setSlotWide(BASEWIDE * RATE);
      setSlotMargin(MARGIN * RATE);
    }, []);

    useEffect(() => {
      setSlotShelf(currentSlotInfo);
      setReactorSlotShelf(currentReactorSlotInfo);
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [currentSlotInfo, currentReactorSlotInfo]);

    useEffect(() => {
      const getWorkbench = async (data: any) => {
        const result: any = await getWorkbenchById(data);
        changeCurrentWorkbench(result);
        setShowLoading(false);
      };

      if (currentDesigner && !currentWorkbench?.id) {
        const { workbench } = currentDesigner;
        getWorkbench({ id: workbench });
      }
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [currentDesigner]);

    useEffect(() => {
      if (currentWorkbench) {
        setShowLoading(false);
        const { row, column } = currentWorkbench;
        setRowList(createList(row || 0));
        setColumnList(createList(column || 0));
      }
    }, [currentWorkbench]);

    const getBottleInfoById = (id: string): ITBottle | null => {
      let temp = null;
      allBottle.some((item) => {
        if (item.id === id) {
          temp = item;
          return true;
        }
        return false;
      });
      return temp;
    };

    const getShelfAndBottleInfo = (name: string): ITShelfBottle => {
      let temp = null;
      let tempBottle = null;
      allShelf.some((item) => {
        if (item.name === name) {
          temp = item;
          return true;
        }
        return false;
      });
      if (temp) {
        const { bottleType } = temp;
        tempBottle = getBottleInfoById(bottleType);
      }
      return {
        shelfInfo: temp,
        bottleInfo: tempBottle,
      };
    };

    const slotClick = (slotname: string) => {
      setPopSlotName(slotname);
      setShowShelfModal(true);
    };

    const closeShelfModal = () => {
      setShowShelfModal(false);
    };

    return (
      <>
        {showLoading && <Spin />}
        {!showLoading && (
          <div className="workbenchplane">
            <div
              className="bord"
              style={{
                paddingLeft: slotMargin,
                paddingTop: slotMargin,
              }}
            >
              {rowList.map((rowItem) => {
                return (
                  <div
                    className="row"
                    key={rowItem}
                    style={{
                      marginBottom: slotMargin,
                      height: slotHeight,
                    }}
                  >
                    {columnList.map((colItem) => {
                      const slotName = `${ROWWORD[rowItem]}${colItem + 1}`;
                    //   const isC3 = slotName === ReactionSlotName;

                      let hasMiniPlane = false;
                      let ShelfMiniPlaneParam: ITShelfBottle = {};
                      let shelfType;
                      // let shelfName = null;
                      if (slotShelf) {
                        let slotshelfInfo = slotShelf[slotName];
                        if (slotshelfInfo) {
                          hasMiniPlane = true;
                          const { shelf } = slotshelfInfo;
                          // shelfName = shelf;
                          ShelfMiniPlaneParam = getShelfAndBottleInfo(shelf);
                          const { shelfInfo } = ShelfMiniPlaneParam;
                          shelfType = shelfInfo?.rackType;
                        }
                      }

                    //   if (isC3 && reactorSlotShelf) {
                    //     const keys = Object.keys(reactorSlotShelf);
                    //     if (keys && keys.length) {
                    //       hasMiniPlane = true;
                    //       let slotshelfInfo = reactorSlotShelf[keys[0]];
                    //       const { shelf } = slotshelfInfo;
                    //       // shelfName = shelf;
                    //       ShelfMiniPlaneParam = getShelfAndBottleInfo(shelf);
                    //       const { shelfInfo } = ShelfMiniPlaneParam;
                    //       shelfType = shelfInfo?.rackType;
                    //     }
                    //   }

                      // 这里需要禁用掉除试剂架之外的架子
                      let display = shelfType !== "reagent";

                      const TipCont = () => (
                        <div
                          className={`hovertip ${langCur === "en" ? "font20" : ""
                            }`}
                        >
                          {lang["langpreparereagent"]}
                        </div>
                      );

                      return (
                        <div
                          className={`slot designer ${display ? "display" : ""
                            }`}
                          style={{
                            width: slotWide,
                            height: slotHeight,
                            marginRight: slotMargin,
                          }}
                          key={colItem}
                          onClick={() => {
                            !display && slotClick(slotName);
                          }}
                        >
                          {!hasMiniPlane && (
                            <div className="slotlabel">{slotName}</div>
                          )}
                          {hasMiniPlane && (
                            <ShelfMiniPlane
                              {...ShelfMiniPlaneParam}
                              slotName={slotName}
                            />
                          )}
                          {!display && <TipCont />}
                        </div>
                      );
                    })}
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {/* 试剂瓶列表和已添加试剂弹窗 */}
        <ShelfModal
          slotName={popSlotName}
          isShow={showShelfModal}
          close={closeShelfModal}
        />
      </>
    );
  })
);

const ReagentTable: FC<TProp | any> = inject("store")(
  observer(({ store }: TProp) => {
    const {
      languageStore: { lang, langCur },
      designerStore: {
        currentDesigner,
        currentReagentsInfo,
        changeReagentAddEditData,
        changShowReagentAddEditModal,
        removeReagent,
      },
      reagentStore: { getReagentInfoById, getReagentUnit, allReagent },
    } = store;

    const [tableData, setTableData] = useState<any>([]);
    useEffect(() => {
      let tempList: any = [];
      if (currentReagentsInfo) {
        const slotNames = Object.keys(currentReagentsInfo);
        slotNames.forEach((slotNameItem) => {
          const bottles = currentReagentsInfo[slotNameItem];
          if (bottles) {
            const bottleNames = Object.keys(bottles);
            bottleNames.forEach((bottleNameItem) => {
              const bottleReagen = bottles[bottleNameItem];
              const {
                reagentId,
                mmol,
                weight,
                volume,
                type,
                id,
                defaultAmount,
              } = bottleReagen;
              const reagentInfo = getReagentInfoById(reagentId);
              if (reagentInfo) {
                const { name, cnname } = reagentInfo;
                const unit = getReagentUnit(reagentId, lang);
                let tempName = name;
                if (langCur === "zhcn") {
                  tempName = cnname || name;
                }
                tempList.push({
                  _id: id,
                  id: reagentId,
                  key: slotNameItem + bottleNameItem,
                  name: tempName,
                  slotName: slotNameItem,
                  bottleName: bottleNameItem,
                  mmol,
                  weight,
                  volume,
                  fillType: type,
                  unit,
                  defaultAmount,
                });
              }
            });
          }
        });
        setTableData(tempList);
      }
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [currentReagentsInfo, allReagent]);

    const modifyItem = (data: any) => {
      const { slotName, amount, id, bottleName, defaultAmount } = data;
      changeReagentAddEditData({
        slotName,
        bottleName,
        reagent: {
          reagentId: id,
          amount,
          defaultAmount,
        },
      });
      changShowReagentAddEditModal(true);
    };

    const deleteItem = async (data: any) => {
      if (currentDesigner) {
        let { id } = currentDesigner;
        const { slotName, bottleName } = data;
        await removeReagent({ slotName, bottleName, designerId: id });
      }
    };

    const columns: ColumnsType<ITColReagent> = [
      {
        title: lang["langshelf"],
        dataIndex: "slotName",
        key: "slotName",
      },
      {
        title: lang["langreagentposi"],
        dataIndex: "bottleName",
        key: "bottleName",
      },
      {
        title: lang["langname"],
        dataIndex: "name",
        key: "name",
        render: (txt: string, record: any) => {
          const { position, id } = record;
          const reagentInfo = getReagentInfoById(id);
          return (
            <Popover
              title={position}
              content={<ReagentPop reagentInfo={reagentInfo} />}
            >
              <Link>{txt}</Link>
            </Popover>
          );
        },
      },
    //   {
    //     title: lang["langamount"],
    //     dataIndex: "defaultAmount",
    //     key: "defaultAmount",
    //     render: (_amount: ITFillReagent, record: any) => {
    //       const { type, weight, volume } = _amount;
    //       let tempAmount = null;
    //       if (type === 1) {
    //         tempAmount = volume;
    //       } else if (type === 2) {
    //         tempAmount = weight;
    //       }
    //       return (
    //         <Popover title="" content={<ReagentAmount data={_amount} />}>
    //           <Link>
    //             {tempAmount}
    //             {record.unit}
    //           </Link>
    //         </Popover>
    //       );
    //     },
    //   },
    //   {
    //     title: lang["langused"],
    //     dataIndex: "used",
    //     key: "used",
    //     render: (txt: any, record: any) => {
    //       const { volume, weight, defaultAmount, fillType, mmol } = record;
    //       let used = null;
    //       let unit = "";
    //       let tempMmol = null;
    //       let tempVolume = null;
    //       let tempWeight = null;
            
    //       if (volume !== null && defaultAmount.volume !== null && defaultAmount.volume !== undefined) {
    //         let temp: any = math.format(math.evaluate(`${defaultAmount.volume} - ${volume}`), FIXEDINDEX);
    //         tempVolume = temp - 0;
    //       }
    //       if (weight !== null && defaultAmount.weight !== null && defaultAmount.weight !== undefined) {
    //         let temp: any = math.format(math.evaluate(`${defaultAmount.weight} - ${weight}`), FIXEDINDEX);
    //         tempWeight = temp - 0;
    //       }
    //       if (mmol !== null && defaultAmount.mmol !== null && defaultAmount.mmol !== undefined) {
    //         let temp: any = math.format(math.evaluate(`${defaultAmount.mmol} - ${mmol}`), FIXEDINDEX);
    //         tempMmol = temp - 0;
    //       }
    //       if (fillType === 1) {
    //         used = tempVolume;
    //         unit = lang["langmlunit"]
    //       } else if (fillType === 2) {
    //         used = tempWeight;
    //         unit = lang["langmg"]
    //       }
    //       let popData = {
    //         mmol: tempMmol,
    //         volume: tempVolume,
    //         weight: tempWeight
    //       }
    //       return <Popover title="" content={<ReagentAmount data={popData} />}><Link>{used}{unit}</Link></Popover>
    //     },
    //   },
      {
        title: lang["langedit"],
        dataIndex: "edit",
        key: "edit",
        width: 110,
        align: "center",
        render: (txt: string, record: any) => {
          return (
            <Space>
              <Tooltip title={lang["langedit"]}>
                <Button
                  type="link"
                  icon={<EditOutlined />}
                  onClick={() => {
                    modifyItem(record);
                  }}
                />
              </Tooltip>
              <Popconfirm
                title={lang["langconfirmdel"]}
                onConfirm={() => {
                  deleteItem(record);
                }}
              >
                <Tooltip title={lang["langdelete"]}>
                  <Button
                    type="link"
                    danger
                    icon={<DeleteOutlined />}
                    disabled={record.defaultAmount - record.amount > 0}
                  />
                </Tooltip>
              </Popconfirm>
            </Space>
          );
        },
      },
    ];

    return (
      <Table
        // onRow={(record: any) => {
        //   return {
        //     onMouseEnter: (e) => {},
        //     onMouseLeave: (e) => {},
        //   };
        // }}
        dataSource={tableData}
        columns={columns}
        bordered
      />
    );
  })
);

const DesignerReagent: FC<TProp | any> = ({ store }: TProp): JSX.Element => {
  const {
    languageStore: { lang },
    designerStore: {
      currentDesigner,
      getDesignerInfo,
      changeReagentAddEditData,
      changShowReagentAddEditModal,
      updateDesigner,
    },
    shelfStore: { getAllShelf, allShelf },
    bottleStore: { getAllBottle, allBottle },
    reagentStore: { getAllReagetList },
    dictionaryStore: { fullDicts, getFullDict },
  } = store;
  const navigate = useNavigate();
  const params = useParams();

  useEffect(() => {
    getAllReagetList();

    if (!allBottle.length) {
      getAllBottle();
    }
    if (!allShelf.length) {
      getAllShelf();
    }
    if (!fullDicts || !fullDicts.length) {
      getFullDict(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (!currentDesigner) {
      const { id } = params;
      if (id) {
        getDesignerInfo({ id });
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentDesigner, params]);

  const clickPrev = () => {
    navigate(`/designer/shelf/${params.id}`);
  };

  const clickNext = async () => {
    const { step, id } = currentDesigner || {};

    if (step && step < 3) {
      await updateDesigner({
        id,
        step: 4,
      });
    }
    navigate(`/designer/reactor/${params.id}`);
  };

  const clearBottleName = () => {
    changeReagentAddEditData(null);
    changShowReagentAddEditModal(false);
  };

  return (
    <Content className="mainLayout">
      {/* 步骤 */}
      <StepTop currentStep={2} />
      <Divider />

      <Row>
        <Col flex="500px">
          <ReagentTable />
        </Col>
        <Col flex="auto">
          {/* 工作台示例 */}
          <DesignerWorkbenchPannel />
        </Col>
      </Row>

      <Row>
        <Col span={24} style={{ textAlign: "center", marginTop: 20 }}>
          <Space>
            <Button onClick={clickPrev}>{lang["langprev"]}</Button>
            <Button type="primary" onClick={clickNext}>
              {lang["langnext"]}
            </Button>
          </Space>
        </Col>
      </Row>

      <ReagentSlotModal close={clearBottleName} />

      <AddReagentModal />

    </Content>
  );
};

export default inject("store")(observer(DesignerReagent));
